import { NSpace, NTable, NPagination, NDatePicker, NCheckbox, NCheckboxGroup,
    NSelect,   } from 'naive-ui'
import MetaHeader from '/src/components/vue-meta/meta-header.vue'
import permissionApi from '/src/api/base/permission_api.js'

import { parseTime } from '/src/utils/tools.js'

const dialogForm = () => {
    return {
        id: null,
        code: '',
        description: '',
        createTime: null,
    }
}

export default {
  components: { NSpace, NTable, NPagination, NDatePicker, NCheckbox, NCheckboxGroup,
    NSelect, MetaHeader, },
  inject: [ "Message", "Dialog" ],
  props: {
    // 是否是从其他组件中掉起此组件
    isModalComponent: { type: Boolean, default: ()=> false }
  },
  data() {
    return {
      datas: [],
      tableLoading: false,

      search: {
        name: null,
      },

      tableCheckList: {}, // 不是数组, key 是选中的下标, value 是否选中 
      tablePage: {
        page: 1,
        size: 10,
        total: 0,
      },

      // 弹出层
      showModal: false,
      isEdit: false,
      dialogFormSaving: false,
      dialogForm: dialogForm(),
      rules: {
        code: [ { required: true, message: '咋个没得代码哦！',trigger: ['blur'] } ],
      },
      parent: {
        loading: false,
        options: [],
      },

      // 分页候选项
      pageSizeOption: [ {label: '10/页', value:10 }, {label: '20/页', value:20 }, {label: '30/页', value:30 } ],
      // pageSizeOption: [ {label: '1/页', value:1 }, {label: '2/页', value:2 }, {label: '3/页', value:3 } ]
    }
  },
  computed: {
    // 表格全选状态
    tableAll() {
      let len = this.datas?.length
      if(len == 0){
        return false
      }
      for(let i=0; i<len; i++) {
        if(!this.tableCheckList[i]) {
          return false
        }
      }
      // 全选中
      return true
    },
    // 表格半选状态
    tableIndeterminate() {
      if(this.tableAll) {
      return false
      }

      let len = this.datas?.length
      for(let i=0; i<len; i++) {
        if(this.tableCheckList[i]) {
          return true
        }
      }
      // 全没选中
      return false
    }
  },
  created() {
    // this.datas = [
    //   { no: 1, code: 'Hello', description: '3:21' },
    //   { no: 2, code: 'Roll with It', description: '3:59' },
    // ]

    this.listData()
  }, 
  methods: {
    parseTime(datetimeStr, formatter) {
      return parseTime(new Date(datetimeStr), formatter)
    },

    // ==弹窗==
    // 新增
    showAdd() {
      this.isEdit = false
      this.showModal = true
      this.dialogForm = dialogForm()
    },
    showEdit(obj) {
      this.isEdit = true
      this.showModal = true

      let cpObj = Object.assign({}, obj)
      cpObj.id = cpObj.id ? cpObj.id + "" : null
      cpObj.pid = cpObj.pid ? cpObj.pid + "" : null
      this.parent.options = [{ label: cpObj.pcode, value: cpObj.pid }]
      this.dialogForm = cpObj      
    },
    close() {
      this.showModal = false
    },
    reset() {
      this.dialogForm = dialogForm()
      this.dialogFormSaving = false
    },

    // 页码变化
    pageChange(page) {
      // console.log("page", page)
      this.tablePage.page = page
      this.listData()
    },
    // 页大小变化
    pageSizeChange(pageSize) {
      //   console.log("pageSize", pageSize)
      this.tablePage.page = 1
      this.tablePage.size = pageSize
      this.listData()
    },

    // 切换选中状态
    toggleCkeckAll() {
      // console.log("tableCheckList", this.tableAll, this.tableIndeterminate, this.tableCheckList)
      if(this.tableIndeterminate) { // 部分选 => 全选
        this.setCheckAll(true)
      } else if(this.tableAll) { // 全选 => 不选
        this.setCheckAll(false)
      } else { // 其他 => 全选
        this.setCheckAll(true)
      }
      // return false
    },
    // 设置全选或取消全选
    setCheckAll(isCheck) {
      let len = this.datas?.length
      for(let i=0; i<len; i++) {
        this.tableCheckList[i] = isCheck
      }
    },
    // 所有选中的数据
    listSelectedDatas() {
      let arr = []
      if(!this.datas) {
        return arr
      }

      let keys = Object.keys(this.tableCheckList)
      for(let i=0; i<keys.length; i++) {
        let key = keys[i]
        if(this.tableCheckList[key]) {
          arr.push(this.datas[key])
        }
      }

      return arr.filter(e => e)
    },

    // ==后台交互==
    saveVo() {
      this.$refs.dialogForm.validate((errors) => {
          if (!errors) {
            let data = Object.assign({}, this.dialogForm)
            this.dialogFormSaving = true
            permissionApi.add(data).then(res => {
              // console.log("saveVo", res)
              this.dialogFormSaving = false
              this.close()
              this.reset()
              this.Message.success( "添加成功", { closable: true, duration: 5000 } )
              this.listData()
            }, res => {
              this.dialogFormSaving = false
              this.Message.error( res.message, { closable: true, duration: 5000 } )
            })
          }
      })
    },
    updateVo() {
      this.$refs.dialogForm.validate((errors) => {
        if (!errors) {
          let data = Object.assign({}, this.dialogForm)
          this.dialogFormSaving = true
          permissionApi.update(data).then(res => {
            // console.log("updateVo", res)
            this.dialogFormSaving = false
            this.close()
            this.reset()
            this.Message.success( "更新成功", { closable: true, duration: 5000 } )
            this.listData() // refresh
          }, res => {
            this.dialogFormSaving = false
            this.Message.error( res.message, { closable: true, duration: 5000 } )
          })
        }
      })
    },
    listData() {
      let data = {
        page: this.tablePage.page,
        size: this.tablePage.size,
        param: {  // permission-vo
            code: this.search.name,
            description: this.search.name,
        }
      }
      this.tableLoading = true
      permissionApi.list(data).then( res => {
        // console.log("list", res)
        this.tableLoading = false
        this.tablePage.total = res.data.total
        let arrList =  res.data.list
        this.datas = arrList
        this.tableCheckList = {}
      }, err => {
        this.tableLoading = false
        this.Message.error( err.message, { closable: true, duration: 5000 } )
      })
    },
    deleteVo(vo) {
      this.Dialog.warning({
        title: '警告',
        content: '你确定要删除吗？',
        positiveText: '确定',
        negativeText: '不确定',
        onPositiveClick: () => {
          let data = {
            id: vo.id
          }
          permissionApi.del(data).then(res => {
            // console.log("updateVo", res)
            this.Message.success( "删除成功", { closable: true, duration: 5000 } )
            this.listData() // refresh
          }, err => {
            this.Message.error( err.message, { closable: true, duration: 5000 } )
          })
        }
      })
    },
    handleSearchParent(value) {
      if(!value) {
        return
      }

      console.log("query", value)
      let data = {
        page: this.tablePage.page,
        size: this.tablePage.size,
        param: {  
            code: value,
            description: value,
        }
      }
      this.parent.loading = false
      permissionApi.list(data).then( res => {
        this.tableLoading = false
        this.tablePage.total = res.data.total
        let arrList =  res.data.list
        
        this.parent.loading = false
        if(arrList) {
          this.parent.options = arrList.map(e => {
            return { label: e.code, value: e.id?e.id+"":null }
          })
        }
      }, err => {
        this.Message.error( err.message, { closable: true, duration: 5000 } )
      })
    },
    // 搜索模板选择
    searchData() {
      this.tablePage.page = 1
      this.listData()
    },
  },
}